package main
import "fmt"

func main() {
	a:=[]int {1,2,3,4,5,6,7,8,9,10}
	c:=make(chan int)
	go sumOfChannel(a[:5],c)
	go sumOfChannel(a[5:],c)
	x,y:= <- c , <-c  //receive from c
	fmt.Println(x,y);
	testBuf()

	fmt.Println("start fib...")
	d:=make(chan int)
	go testFib(d,20)
	for i:= range d{
		fmt.Println(i)
	}

	fmt.Println("start fib2...")
	e:=make(chan int)
	f:=make(chan int)
	go func() {
		for i:=0;i<10;i++{
			fmt.Println(<- e)
		}
		f <- 0
	}()

	testFib2(e,f)

}

func testBuf()  {
	c := make(chan int, 3)//修改2为1就报错，修改2为3可以正常运行
	c <- 1
	c <- 2
	fmt.Println(<-c)
	fmt.Println(<-c)
}

func sumOfChannel(a[] int,c chan int )  {
	total:=0
	for _,v:= range a  {
		total+=v
	}
	c <- total //send total to chanel
}


func testFib(c chan int ,n int )  {
	x,y := 1,1
	for i:=0;i<n ;i++  {
		c <- x
		x,y = y,x+y
	}
	close(c)
}

func testFib2(c,d chan int)  {
	x,y := 1,1
	for{
		select {
		case c <- x :
			x,y = y,x+y
		case  <- d :
			fmt.Println("quite")
			return
		}
	}
}
